package com.pdd.controller;

import com.pdd.beans.Category;
import com.pdd.dto.DTO;
import com.pdd.service.CategoryService;
import com.pdd.util.UploadUtil;
import com.pdd.vo.category.CategoryAddVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@CrossOrigin(origins = { "*" })
@Api(description = "商品分类接口")
public class CategoryController {

    @Autowired
    @Setter
    private CategoryService categoryService;

    //region Description 添加商品分类
    @ApiOperation(value = "添加商品分类")
    @RequestMapping(value = "/category",method = RequestMethod.POST)
    @ResponseBody
    public DTO add(MultipartFile logo, CategoryAddVO vo, HttpServletRequest request){

        //执行上传
        String targetName = UploadUtil.upload(logo,request);

        System.out.println(vo);
        System.out.println(logo);

        //1. 封装参数
        Category category = new Category();
        category.setPid(vo.getPid());
        category.setName(vo.getName());
        category.setLogo(targetName);
        category.setOrder(vo.getOrder());

        //2. 执行新增
        boolean result = categoryService.addCategory(category);

        //3. 创建DTO,并返回
        if(result){
            return DTO.success();
        }else{
            return DTO.error();
        }
    }
    //endregion

    //region Description 获得所有一级分类商品信息
    @ApiOperation(value = "获得所有一级分类商品信息")
    @RequestMapping(value = "/category",method = RequestMethod.GET)
    @ResponseBody
    public DTO get(){

        //1. 执行查询操作
        List<Category> list = categoryService.getByPid(null);

        //2. 封装DTO
        DTO dto = new DTO(list);
        //3. 返回结果
        return dto;
    }
    //endregion

    //region Description 获得指定二级分类商品信息
    @ApiOperation(value = "获得指定二级分类商品信息")
    @RequestMapping(value = "/category/{pid}",method = RequestMethod.GET)
    @ResponseBody
    public DTO getByPid(@ApiParam(value = "父级分类编号") @PathVariable(name = "pid") Integer pid){
        Integer param = pid==0?null:pid;

        //1. 执行查询操作
        List<Category> list = categoryService.getByPid(param);

        //2. 封装DTO
        DTO dto = new DTO(list);

        //3. 返回DTO
        return dto;
    }
    //endregion
}
